package com.lg.wechat.common.handler;
import java.lang.reflect.Method;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.lg.utils.StringUtils;
import com.lg.wechat.common.annotation.Clear;
import com.lg.wechat.utils.Constant;
import com.lg.wechat.utils.CookieUtil;
import me.chanjar.weixin.mp.api.WxMpService;
public class WxAuthenInterceptor implements HandlerInterceptor {
	 private static final Logger log = LoggerFactory.getLogger(WxAuthenInterceptor.class);  
	  @Autowired
	  private WxMpService wxService;
	 /**   
     * 进入controller层之前拦截请求   
     * @param httpServletRequest   
     * @param response   
     * @param o   
     * @return   
     * @throws Exception   
     */    
    @Override    
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {  
    	long starTime=System.currentTimeMillis();
    	boolean flag=false;//默认拦截
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        Clear beanClear= handlerMethod.getBean().getClass().getAnnotation(Clear.class);//controller 清除拦截器
        Clear methodClear=method.getAnnotation(Clear.class);//方法清除拦截器
        if(handler instanceof HandlerMethod){
        	flag=false;
        } 
        else{
        	 flag=true;
        	 return flag;//资源文件不拦截直接跳过
        }
        //首先判断方法上是否有清除拦截,并且是否清除了该授权拦截了	
        flag=handClear(beanClear);//判断controller是否需要拦截
        if(!flag){
        //如果controller不拦截的话则表明controller有注解，无需再判断方法上是否拦截了
        //如果controller拦截的话则表明controller要么无注解，要么，有注解但是并没有指定清除该拦截器注解这个时候需要判断方法上是否有拦截
        flag=handClear(methodClear);	
        }
        if(!flag){
        	//拦截
      	    Cookie cookie= CookieUtil.getCookieByName(request,Constant.Token);
            if(cookie==null||StringUtils.isEmpty(cookie.getValue())){
            	String oauthUrl=wxService.oauth2buildAuthorizationUrl("http://154jg07681.iask.in/wx/oauth/index","snsapi_userinfo",request.getServletPath());
            	response.sendRedirect(oauthUrl);
            	return false;
            }else{
            	return true;
            }
        }
        long endTime=System.currentTimeMillis();
        log.error("---------------执行时间-------------------------0"+(endTime-starTime)/1000);    
        return flag;
           
    }

    private boolean handClear(Clear handClear) throws InstantiationException, IllegalAccessException{
    	boolean f=false;//默认拦截
    	if(handClear==null){//没有清除注解，直接拦截
    		return f;
    	}else{//有清除注解
    		Class<? extends HandlerInterceptor>[] handlers= handClear.value();
    		if(handlers.length>0){//指定了清除拦截器
    			for(Class<? extends HandlerInterceptor> hand:handlers){
        			if(hand.newInstance() instanceof  WxAuthenInterceptor){
        				f=true;
            			break;
        			}
        		}
    		}else if(handlers.length==0){//未指定清除默认全部清除
    			f=true;
    		}
    	}
    	return f;
    }
  

    @Override    
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {    
        log.info("--------------处理请求完成后视图渲染之前的处理操作---------------");    
    }    
    
    @Override    
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {    
        log.info("---------------视图渲染之后的操作-------------------------0");    
    }    
}
